package com.sy.simpleegg.mvp.model

import com.sy.simpleegg.base.BaseModel
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.mvp.contract.UpgradeContract
import com.sy.simpleegg.upgrade.FileDownloader
import com.sy.simpleegg.util.FileUtil
import java.io.File


class UpgradeModel(val listener: DownloadListener): BaseModel(), UpgradeContract.Model {

    override suspend fun downloadApp(savePath: String, apkName: String, url: String) {
        FileDownloader.download(savePath, apkName, url, object : FileDownloader.OnDownloadListener {
            override fun onDownloadSuccess(loadUrl: String?, filePath: String?) {
                logFile("下载APP成功")
                if (loadUrl != null && filePath != null){
                    val copyPath = filePath.substring(0, filePath.length - 4) + "/1.apk"
                    if (FileUtil.copyFile(filePath, copyPath)){
                        val apkFile = File(copyPath)
                        if (apkFile.exists()){
                            logFile("APK文件存在")
                        }else{
                            logFile("APK文件不存在")
                        }
                        listener.downloadSuccess(copyPath)
                    }
                }
            }

            override fun onDownloading(progress: Long, total: Long) {
                val p = (progress.toFloat() / total.toFloat() * 100).toInt()
                logFile("下载APP进度$p")
                listener.refreshProgress(p)
            }

            override fun onDownloadFailed(errorInfo: String?) {
                logFile("下载APP失败$errorInfo")
                listener.failed(errorInfo?:"")
            }

        })
    }

    interface DownloadListener{
        fun downloadSuccess(path: String)

        fun failed(msg: String)

        fun refreshProgress(progress: Int)
    }

}